﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BudgetManager.Entities;
using BudgetManager.Data;
using BudgetManager.Resources;

namespace BudgetManager
{
    public partial class Categories : PhoneApplicationPage
    {
        #region PROPERTIES
        ApplicationBarIconButton delete;
        ApplicationBarIconButton multiselect;
        public List<string> CategoryList
        {
            get
            {
                return new BudgetMgrDAL().LoadCategories().Select(c => c.Name).ToList();
            }
        }
        #endregion
        public Categories()
        {
            InitializeComponent();
            DefineAppBarButtons();
            this.Loaded += Categories_Loaded;
        }

        #region EVENT_HANDLERS
        /// <summary>
        /// Event triggered when Categories page is loaded
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">routedEvent arguments</param>
        void Categories_Loaded(object sender, RoutedEventArgs e)
        {
            ApplicationBar.Buttons.Add(multiselect);
            categoriesList.ItemsSource = CategoryList;
            if (CategoryList != null && CategoryList.Count > 0)
                txtCategoriesList.Visibility = System.Windows.Visibility.Visible;
            //categoriesList.ItemsSource = new List<string>() { "ASD", "asd", "xc", "ewf", "ASD", "asd", "xc", "ewf", "ASD", "asd", "xc", "ewf", "ASD", "asd", "xc", "ewf" };
        }

        /// <summary>
        /// MultiSelect selection event for WPToolKit control
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event argument</param>
        void multiselect_Click(object sender, EventArgs e)
        {
            categoriesList.IsSelectionEnabled = true;
        }

        /// <summary>
        /// Delete appbarbutton selection event. Handles deletion  of categories and related expense items
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">Event arguments</param>
        void delete_Click(object sender, EventArgs e)
        {
            var selectedItems = categoriesList.SelectedItems;
            string Categories = "\n";
            foreach (var item in selectedItems)
            {
                Categories += item.ToString() + "\n";
            }
            var mBoxResult = MessageBox.Show(String.Format(AppResources.DeleteWarningMessageText, Categories.ToUpper()), AppResources.WarningMessageText, MessageBoxButton.OKCancel);
            switch (mBoxResult)
            {
                case MessageBoxResult.OK:
                    {
                        new BudgetMgrDAL().DeleteCategory(selectedItems);
                        //TODO
                        //LoadCategories();
                        NavigationService.Navigate(new Uri(String.Format("/Categories.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
                        break;
                    }
                case MessageBoxResult.Cancel:
                default:
                    {
                        categoriesList.IsSelectionEnabled = false;
                        break;
                    }
            }  
        }

        /// <summary>
        /// Gets triggered whenever user selects/deselects items from the categories list. Used for delete
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">Event args</param>
        private void categoriesSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (categoriesList.SelectedItems.Count > 0)
            {
                ApplicationBar.Buttons.Remove(multiselect);
                ApplicationBar.Buttons.Add(delete);
            }
            else
            {
                ApplicationBar.Buttons.Add(multiselect);
                ApplicationBar.Buttons.Remove(delete);
            }
        }

        /// <summary>
        /// Gets triggered when user adds a anew category.
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">event args</param>
        private void addCategory(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (txtNewCategory.Text != "")
            {
                bool isValid = validateCategory(txtNewCategory.Text);
                if (isValid)
                {
                    Category category = new Category();
                    category.Name = txtNewCategory.Text.ToUpper();
                    txtNewCategory.Text = "";
                    new BudgetMgrDAL().SaveCategory(category);
                    CategoryList.Add(category.Name); 
                    NavigationService.Navigate(new Uri(String.Format("/Categories.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
                }
                else
                {
                    MessageBox.Show(String.Format(AppResources.UniqueCategoryValidationText, txtNewCategory.Text.ToUpper()), AppResources.WarningMessageText, MessageBoxButton.OK);
                    txtNewCategory.Text = "";
                }
            }
        }

        private void onTextChanged(object sender, TextChangedEventArgs e)
        {
            if ((sender as TextBox).Text != "")
            {
                btnAdd.IsEnabled = true;
            }
            else
            {
                btnAdd.IsEnabled = false;
            }
        }
        #endregion

        # region OVERRIDED_METHODS
        /// <summary>
        /// Back press key event
        /// </summary>
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (categoriesList.IsSelectionEnabled == true)
            {
                categoriesList.IsSelectionEnabled = false;
                e.Cancel = true;
            }
            else
            {
                base.OnBackKeyPress(e);
            }
        }

        /// <summary>
        /// OnNavigated event
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string id = string.Empty;
            if (NavigationContext.QueryString.TryGetValue("id", out id))
            {
                if (NavigationService.CanGoBack)
                    NavigationService.RemoveBackEntry();
            }
        }
        #endregion

        #region HELPER_METHODS

        /// <summary>
        /// Define AppBarButtons used in categories Page
        /// </summary>
        private void DefineAppBarButtons()
        {
            //delete button to be displayed when there is any selected item
            delete = new ApplicationBarIconButton(new Uri("/Toolkit.Content/ApplicationBar.Delete.png", UriKind.RelativeOrAbsolute));
            delete.Text = AppResources.DeleteText;
            delete.Click += delete_Click;

            //MultipleSelect button 
            multiselect = new ApplicationBarIconButton(new Uri("/Toolkit.Content/ApplicationBar.Select.png", UriKind.RelativeOrAbsolute));
            multiselect.Text = AppResources.SelectText;
            multiselect.Click += multiselect_Click;
        }

        /// <summary>
        /// Validates Uniqueness of categories in the database. For performance purpose, the localdata is scanned and then inserted to db.
        /// </summary>
        /// <param name="categoryName">Name of the category to be added</param>
        /// <returns>status of uniquess</returns>
        public bool validateCategory(string categoryName)
        {
            bool isValid = false;
            var category = CategoryList.FirstOrDefault(c => c == categoryName.ToUpper());
            isValid = category != null ? false : true;
            return isValid;
        }
        #endregion

        
    }
}